package com.stooges.adjustment.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSession;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stooges.adjustment.entity.ApplyLog;
import com.stooges.adjustment.entity.LocalOauth;
import com.stooges.adjustment.entity.Teacher;
import com.stooges.adjustment.form.AccountForm;
import com.stooges.adjustment.form.ApplyAlterForm;
import com.stooges.adjustment.form.ApplyConditionForm;
import com.stooges.adjustment.util.Constants;
import com.stooges.adjustment.util.Md5Util;
import com.stooges.adjustment.view.ApplierView;
import com.stooges.adjustment.view.ApplyView;
import com.stooges.adjustment.view.MajorCollectionView;

/**
 * 老师逻辑处理
 * @author 张超
 *
 */
@Service
public class TeacherService {
	@Resource
	private SqlSession sqlSession;
	/**
	 * 检查重复用户名重复性
	 * @param username 用户名
	 * @param errorMap 错误
	 * @return 是否重复
	 */
	public boolean validateAccountDuplicate(String username,Map<String,String> errorMap){
		LocalOauth localOauth = sqlSession.selectOne("localOauthDao.findOauthByUsername",username);
		if(localOauth==null){
			return false;
		}else{
			errorMap.put("error","用户名重复");
			return true;
		}
	}
	/**
	 * 添加帐号
	 * @param accountForm 帐号表单
	 * @param operatorId 操作者ID
	 * @return
	 */
	@Transactional(rollbackFor=Exception.class)
	public boolean addAccount(AccountForm accountForm,Long operatorId)throws Exception{
		//查询所在学院
		Teacher openAccountTeachher = sqlSession.selectOne("teacherDao.findAccountByOauthId",operatorId);
		
		//组装数据
		LocalOauth localOauth = new LocalOauth();
		String username = accountForm.getUsername();
		if(Character.isDigit(username.charAt(0))){
			username = "T"+username;
		}
		localOauth.setUsername(username);
		localOauth.setUsername(accountForm.getUsername());
		localOauth.setPassword(Md5Util.MD5(accountForm.getPassword()));
		if(accountForm.getAccountType()==Constants.ACCOUNT_TYPE_OPEN){
			localOauth.setRoleId(Constants.ROLE_TEACHER1);
		}else{
			localOauth.setRoleId(Constants.ROLE_TEACHER2);
		}
		localOauth.setStatus(Constants.LOCAL_OAUTH_STATUS_ACTIVATED);
		localOauth.setCreateTime(System.currentTimeMillis()/1000);
		
		//添加帐号信息
		sqlSession.insert("localOauthDao.saveLocalOauth", localOauth);
		Teacher teacher = new Teacher();
		teacher.setLocalOauthId(localOauth.getId());
		teacher.setCollegeId(openAccountTeachher.getCollegeId());
		teacher.setName(accountForm.getName());
		return sqlSession.insert("teacherDao.saveTeacher",teacher)>0;
	}
	/**
	 * 更新学生申请状态
	 * @param applyAlterForm 要修改的申请信息表单
	 * @param operatorId 操作者ID
	 * @return
	 * @throws Exception
	 */
	@Transactional(rollbackFor=Exception.class)
	public boolean updateApplyStatus(ApplyAlterForm applyAlterForm)throws Exception{
		if(applyAlterForm==null){
			return false;
		}
		//生成操作日志
		ApplyLog applyLog = new ApplyLog();
		applyLog.setApplierId(applyAlterForm.getStudentId());
		applyLog.setOperateId(applyAlterForm.getOperatorId());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        String dateNowStr = sdf.format(new Date());
		applyLog.setOperateDate(dateNowStr);
		String json = JSON.toJSONString(applyLog);
		applyAlterForm.setAllLog(json);
		applyAlterForm.setLastLog(json);
		boolean updateStudentResult = true;
		if (applyAlterForm.getStatus().equals(Constants.TARGET_STATUS_ENROLL)){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("localOauthId", applyAlterForm.getStudentId());
			map.put("admissionStatus", Constants.STUDENT_STATUS_ENROLL);
			updateStudentResult = sqlSession.update("studentDao.updateStudentStatus",map)>0;
		}
		if(updateStudentResult){
			return sqlSession.update("targetDao.updateApplyStatus",applyAlterForm)>0;
		}else{
			return false;
		}
	}
	
	/**
	 * 根据条件查询所有的申请记录
	 * @param applyConditionForm 申请条件
	 * @return
	 */
	public PageInfo<ApplyView> findAllApply(ApplyConditionForm applyConditionForm) {
		int pageNum = 1;
		int pageSize = 10;
		if(applyConditionForm!=null){
			if(applyConditionForm.getPageNum()!=null){
				pageNum = applyConditionForm.getPageNum();
			}
			if(applyConditionForm.getPageSize()!=null){
				pageSize = applyConditionForm.getPageSize();
			}
		}
		PageHelper.startPage(pageNum, pageSize);
		List<ApplyView> applyList = sqlSession.selectList("targetDao.findAllApply",applyConditionForm);
		return new PageInfo<ApplyView>(applyList);
	}
	
	/**
	 * 根据学生ID查询申请者全部信息
	 * @param studentId 学生ID
	 * @param operateId 操作者ID
	 * @param roleId 操作者权限ID
	 * @return 
	 */
	public ApplierView findApplierDetail(Long studentId, Long operateId,Integer roleId) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("studentId", studentId);
		map.put("operateId", operateId);
		map.put("roleId", roleId);
		return sqlSession.selectOne("targetDao.findApplierDetail",map);
	}
	/**
	 * 根据登录者ID查询所有专业方向集合
	 * @param id 登录者ID
	 * @return
	 */
	public MajorCollectionView findMajorCollectByOauthId(Long id) {
		return sqlSession.selectOne("collegeDao.findMajorCollectByOauthId",id);
	}
	/**
	 * 设置输出单元格的格式
	 * @param outWorkbook   Excel文件夹
	 * @param inRow         要读取的模板的行
	 * @param outRow        要输出的行
	 * @param i             第i列
	 * @return              设置好格式的单元格
	 */
	public HSSFCell getOutCell(HSSFWorkbook outWorkbook,HSSFRow inRow,HSSFRow outRow,int i){
		HSSFCell inCell = inRow.getCell(i);
		HSSFCellStyle inCellStyle = inCell.getCellStyle();
		HSSFCellStyle outCellStyle = outWorkbook.createCellStyle();
        outCellStyle.cloneStyleFrom(inCellStyle);
        HSSFCell outCell = outRow.createCell(i);
        outCell.setCellStyle(outCellStyle);
        return outCell;
	}
	/**
	 * 根据条件查询所有导出excel用的申请记录
	 * @param applyConditionForm
	 * @return
	 */
	public List<ApplyView> findExcelApplys(ApplyConditionForm applyConditionForm) {
		if(applyConditionForm==null){
			applyConditionForm = new ApplyConditionForm();
		}
		List<ApplyView> applyList = sqlSession.selectList("targetDao.findExcelApplys",applyConditionForm);
		return applyList;
	}
}
